<template>
  <el-drawer
      v-model="showFlag"
      append-to-body
      :before-close="cancel">
    <div style="margin: 20px">
      <el-form :model="refForm" :rules="rules" ref="formView" label-position="top" size="default">

        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="refForm.roleName"/>
        </el-form-item>

        <el-form-item label="权限标识" prop="roleKey">
          <el-input v-model="refForm.roleKey"/>
        </el-form-item>

        <el-form-item label="排序" prop="roleSort">
          <el-input-number :min="0" v-model="refForm.roleSort"/>
        </el-form-item>

        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="refForm.state">
            <el-radio v-for="item in stateOptions" :label="item.dictValue">{{ item.dictLabel }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="资源权限" prop="perms">
          <el-tree
              style="width: 100%"
              ref="menuTreeRef"
              node-key="menuId"
              :data="menuTreeList"
              :props="{label:'title',children:'children'}"
              show-checkbox
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input :autosize="{ minRows: 2, maxRows: 4 }"
                    type="textarea" v-model="refForm.remark"/>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div style="text-align: center;margin-bottom: 10px">
        <el-button size="default" @click="cancel()">取消</el-button>
        <el-button size="default" type="primary" @click="subimt()"  v-auths="['system-role-update','system-role-add']">提交</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup>
import {treeForManage} from "/@/api/system/menu";
import {addRole, updateRole} from "/@/api/system/role";
import {ElMessage} from "element-plus";

const showFlag = ref(false)
const {proxy} = getCurrentInstance()
const emits = defineEmits(['ok'])
let refForm = reactive({
  roleId: undefined,
  roleName: undefined,
  roleKey: undefined,
  roleSort: 1,
  state: '0',
  perms: [],
  remark: undefined
})
const tempCheckNodes = ref([])
const menuTreeRef = ref()

const rules = reactive({
  roleName: [{required: true, message: '请输入角色名称', trigger: 'blur'}],
  roleKey: [{required: true, message: '请输入角色标识', trigger: 'blur'}],
})
const cancel = () => {
  proxy.$refs.formView.clearValidate()
  proxy.$refs.formView.resetFields()
  menuTreeRef.value.setCheckedKeys([])
  tempCheckNodes.value = []
  refForm.roleId=undefined
  showFlag.value = false
}
const subimt = async () => {
  let checkedKeys = menuTreeRef.value.getCheckedKeys()
  let halfCheckeys = menuTreeRef.value.getHalfCheckedKeys()
  refForm.perms = halfCheckeys.concat(checkedKeys)
  await proxy.$refs.formView.validate((valid) => {
    if (valid) {
      if (!refForm.roleId) {
        addRole(refForm).then(res => {
          ElMessage.success(res.msg)
          cancel()
          emits('ok')
        })
      } else {
        updateRole(refForm).then(res => {
          ElMessage.success(res.msg)
          cancel()
          emits('ok')
        })
      }
    }
  })
}
const stateOptions = ref([])

const menuTreeList = ref([])

const open = (node) => {
  if (node) {
    refForm.roleId = node.roleId
    refForm.roleName = node.roleName
    refForm.roleKey = node.roleKey
    refForm.roleSort = node.roleSort
    refForm.state = node.state
    refForm.perms = node.perms
    refForm.remark = node.remark
    // 处理资源菜单数据回显
    showChecked(menuTreeList.value, refForm.perms)
  }
  showFlag.value = true
  setTimeout(function () {
    menuTreeRef.value.setCheckedKeys(tempCheckNodes.value)
  }, 100)

}


const showChecked = (menuList, fromArr) => {

  menuList.forEach(menu => {
    if (!menu.children) {
      if (fromArr.includes(menu.menuId)) {
        tempCheckNodes.value.push(menu.menuId)
      }
    } else {
      showChecked(menu.children, fromArr)
    }
  })
}

defineExpose({
  open
})

onBeforeMount(() => {
  proxy.$dictOptions('sys_common_status').then(res => {
    stateOptions.value = res.data
  })
  treeForManage().then(res => {
    menuTreeList.value = res.data
  })
})


</script>

<style scoped>

</style>
